// DOM加载完成后执行
document.addEventListener("DOMContentLoaded", function () {
    // 如果页面中有带有 original 属性的 img 元素，执行懒加载逻辑
    var imgs = Array.from(document.querySelectorAll("img[original]"));
    if (imgs.length > 0) {
        lazyload(imgs, {
            placeholder: "/images/qq.gif"
        });
    }
});

// 表单搜索关键字检查，至少4个字符
function CheckSearch(form) {
    if (form.keyword.value.length < 4) {
        alert("搜索字符至少要4个字符！");
        form.keyword.focus();
        return false;
    }
    return true;
}

// 产品搜索关键词不能为空
function CheckProSearch(form) {
    if (form.keyword.value === "") {
        alert("请填写搜索关键词！");
        form.keyword.focus();
        return false;
    }
    return true;
}

// 提交询价表单检查
function CheckSubmit(form) {
    var flag = false;
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].name === "id" && form.elements[i].checked === true) {
            flag = true;
            break;
        }
    }
    if (!flag) {
        alert("请先选择您要询价的Ic型号!");
        return false;
    } else {
        if (checkInputEmail(form.mail.value, 'ch')) {
            return false;
        }
    }
    if (form.contact.value === "") {
        alert("请填写联系公司/人!");
        form.contact.focus();
        return false;
    }
    if (form.tel.value === "") {
        alert("请填写您的联系电话!");
        form.tel.focus();
        return false;
    }
    return true;
}

// 反馈表单检查
function CheckFeedback(form) {
    if (form.company.value === "") {
        alert("请填写公司名称！");
        form.company.focus();
        return false;
    }
    if (form.contact.value === "") {
        alert("请填写联系人！");
        form.contact.focus();
        return false;
    }
    if (form.tel.value === "") {
        alert("请填写联系电话！");
        form.tel.focus();
        return false;
    }
    if (form.content.value === "") {
        alert("请填写留言内容!");
        form.content.focus();
        return false;
    }
    return true;
}

// 根据搜索类型改变是否禁用searchtype下拉框
function changeselect() {
    var selecttype = document.all ? document.all.searchcontent.value : document.querySelector("[name='searchcontent']").value;
    var searchtypeElem = document.all ? document.all.searchtype : document.querySelector("[name='searchtype']");
    if (selecttype == 2 || selecttype == 3 || selecttype == 4) {
        searchtypeElem.disabled = true;
    } else if (selecttype == 1 || selecttype == 5) {
        searchtypeElem.disabled = false;
    }
}

// 更换CSS样式文件路径
function changecolor(cssfile) {
    var linkElem = document.getElementById("cssfilepath");
    if (linkElem) {
        linkElem.setAttribute("href", cssfile);
    }
}

// 页头搜索功能，根据当前选择和语言类型，设置表单提交地址、校验函数及提示文字
function headersearch(obj, currVal, langType) {
    var frm = document.getElementById("frmheadersearch");
    var keyword = document.getElementById("keyword");
    if (langType == 1) {
        if (currVal == 1) {
            frm.action = "/stock/";
            frm.onsubmit = function () { return CheckSearch(frm); };
            keyword.placeholder = "请输入IC型号";
        } else {
            frm.action = "/product/";
            frm.onsubmit = function () { return CheckProSearch(frm); };
            keyword.placeholder = "请输入产品关键词";
        }
    } else if (langType == 2) {
        if (currVal == 1) {
            frm.action = "/english/stock/";
            frm.onsubmit = function () { return CheckSearch(frm); };
            keyword.placeholder = "Please Input IC Model To Search！";
        } else {
            frm.action = "/english/product/";
            frm.onsubmit = function () { return CheckProSearch(frm); };
            keyword.placeholder = "Please Input Keyword To Search！";
        }
    }
    var searchcontent = document.getElementById("searchcontent");
    if (searchcontent) {
        searchcontent.value = currVal;
    }

    // 样式切换，设置选中状态
    var siblings = obj.parentNode.children;
    for (var i = 0; i < siblings.length; i++) {
        siblings[i].classList.remove("searchtitle");
    }
    obj.classList.add("searchtitle");

    // 把当前点击项移到父元素开头
    var parentChoose = obj.closest(".search .choose");
    if (parentChoose) {
        parentChoose.insertBefore(obj, parentChoose.firstChild);
    }
}

// 禁用右键菜单及文本选择，用于限制特定会员访问
(function () {
    var urls = "www.szkdnx.com";
    urls = urls.split(',');
    var u = location.hostname;
    var bl = false;
    for (var i = 0; i < urls.length; i++) {
        if (urls[i] === u) bl = true;
    }
    if (bl) {
        document.oncontextmenu = function () { return false; };
        document.onselectstart = function () { return false; };
    }
})();

// 添加到收藏夹（通用，兼容旧浏览器）
function addBookmark(title, url) {
    if (window.sidebar) {
        window.sidebar.addPanel(title, url, "");
    } else if (document.all) {
        window.external.AddFavorite(url, title);
    } else if (window.opera && window.print) {
        return true;
    }
}

// 邮箱格式校验，返回 true 表示校验失败（不合格）
function checkInputEmail(v, e) {
    var reg = /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/;
    var f = reg.test(v);
    if (!f) {
        if (e == "ch") {
            alert("请输入正确的邮箱，以便方便联系您！");
        } else {
            alert("Please enter a valid e-mail in order to facilitate contact you!");
        }
        return true;
    }
    return false;
}


// 图片等比例缩放，传入img元素和最大宽高
function DrawImage(ImgD, FitWidth, FitHeight) {
    var image = new Image();
    image.src = ImgD.src;
    image.onload = function () {
        if (image.width > 0 && image.height > 0) {
            if (image.width / image.height >= FitWidth / FitHeight) {
                if (image.width > FitWidth) {
                    ImgD.width = FitWidth;
                    ImgD.height = (image.height * FitWidth) / image.width;
                } else {
                    ImgD.width = image.width;
                    ImgD.height = image.height;
                }
            } else {
                if (image.height > FitHeight) {
                    ImgD.height = FitHeight;
                    ImgD.width = (image.width * FitHeight) / image.height;
                } else {
                    ImgD.width = image.width;
                    ImgD.height = image.height;
                }
            }
        }
    }
}

// 表单提交校验（型号、联系人、邮箱、电话）
function CheckSubmit83(form) {
    if (form.xinghao.value === "") {
        alert("请填写型号!");
        form.xinghao.focus();
        return false;
    }
    if (form.contact.value === "") {
        alert("请填写联系公司/人!");
        form.contact.focus();
        return false;
    }
    if (form.mail.value === "") {
        alert("请填写Email!");
        form.mail.focus();
        return false;
    }
    if (form.tel.value === "") {
        alert("请填写您的联系电话!");
        form.tel.focus();
        return false;
    }
    return true;
}

// 英文版表单提交校验
function CheckSubmit83en(form) {
    if (form.xinghao.value === "") {
        alert("Please Input Part Number!");
        form.xinghao.focus();
        return false;
    }
    if (form.contact.value === "") {
        alert("Please Input Contact person!");
        form.contact.focus();
        return false;
    }
    if (form.mail.value === "") {
        alert("Please Input Email!");
        form.mail.focus();
        return false;
    }
    if (form.tel.value === "") {
        alert("Please Input Tel!");
        form.tel.focus();
        return false;
    }
    return true;
}

// 密码强度检测对象
var Yxj_Function = {
    // 获取密码等级：0-4
    GetPassWordLevel: function (pw) {
        var v = pw, l = v.length, min = 6, level = 0;
        if (l < min) {
            if (l > 0) level = 1;
        } else {
            if (/^(\d{6,9}|[a-z]{6,9}|[A-Z]{6,9})$/.test(v)) level = 1;
            else if (/^[^a-z\d]{6,8}$/i.test(v) || !/^(\d{6,9}|[a-z]{6,9}|[A-Z]{6,9})$/.test(v)) level = 2;
            if (!/^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/.test(v))
                level = l < 10 ? 3 : 4;
        }
        return level;
    },
    // 根据等级设置背景位置，实现密码强度条的变化
    DisplayLevel: function (psw, objID) {
        var n = Yxj_Function.GetPassWordLevel(psw);
        var ele = document.getElementById(objID);
        if (!ele) return;
        switch (n) {
            case 0:
                ele.style.backgroundPosition = "0 0";
                break;
            case 1:
                ele.style.backgroundPosition = "0 -26px";
                break;
            case 2:
                ele.style.backgroundPosition = "0 -52px";
                break;
            case 3:
                ele.style.backgroundPosition = "0 -78px";
                break;
            case 4:
                ele.style.backgroundPosition = "0 -104px";
                break;
            default:
                ele.style.backgroundPosition = "0 0";
                break;
        }
    }
};






//🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥============================
///添加自定义的公用html模块
function loadCustom({ selector, defaultPath, callback }) {
    const container = document.querySelector(selector);
    if (!container) {
        console.error(`No container found for selector: ${selector}`);
        return;
    }

    const path = container.getAttribute(selector.replace(/[\[\]]/g, '')) || defaultPath;
    fetch(path)
        .then(response => response.text())
        .then(data => {
            container.innerHTML = data;

            // 执行其中的 script
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = data;
            const scripts = tempDiv.querySelectorAll('script');

            scripts.forEach(oldScript => {
                const newScript = document.createElement('script');

                // 如果有 src 则处理外链脚本
                if (oldScript.src) {
                    newScript.src = oldScript.src;
                } else {
                    newScript.textContent = oldScript.textContent;
                }

                // 将脚本插入到 body 中（或 container 中）
                document.body.appendChild(newScript);
            });

            if (typeof callback === 'function') {
                callback(container);
            }
        })
        .catch(err => {
            console.error(`Failed to load custom from ${path}:`, err);
        });
}



// 挂载到全局 window
window.loadCustom = loadCustom;
